package com.epro.dx.activity.coupon.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.AbsListView.OnScrollListener;
import android.widget.RelativeLayout;

import com.epro.dx.R;
import com.epro.dx.activity.HomeActivity.OnTouchEventListenner;
import com.epro.dx.activity.LandingPageActivity;
import com.epro.dx.activity.SpecialActivity;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.fragment.BaseLoadAndEmptyDataFragment;
import com.epro.dx.listenner.OnViewGroupScrollListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshGridView;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CouponActiveModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

@SuppressLint("ValidFragment")
public class LandingPageCategoryFragment extends BaseLoadAndEmptyDataFragment
		implements OnViewGroupScrollListenner/*, OnSortChangeListenner */{
	private static final String TAG = "LandingPageCategoryFragment";

	private PullToRefreshGridView gridViewLayout;
	
	private RelativeLayout productsLayout;

	/**
	 * 商品列表适配器
	 */
	private ProductListAdapter adapterProduct;

	private View rootView;

	/**
	 * 接口返回商品列表
	 */
	private ArrayList<ProductModel> productsList = new ArrayList<ProductModel>();

	private int pageIndex = 0;

	private Context mContext;

	private int categoryId;
	
	private int position;

	private ArrayList<ProductModel> productlist;

	private String couponCode;
	
	private int firstVisiblePosition;
	
	private boolean isLoading;
	
	private boolean isReLoad;
	
	// 返回top按钮
	private ImageButton toTop;
	
	private String sortType=Constant.SORT_POPULARITY;
	
	private OnFragmentCreateViewCalled listenner;
	
	//列表第一个可见的Item下表
	private int currentPosition=-1;
	
	private OnFlingStateChangedListener onFlingStateChangedListener;
	
	private int firstVisibalNum = -1;
	public boolean mIsScroll2Top = false;
	private boolean isOnTouching = false;
	private boolean isFirstIn = true;

	private String currencyCode;

	private String currencyCodeStr;
	
	private Tracker tracker;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tracker = ((DXApplication) getActivity().getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		position=getArguments().getInt("Position");
		categoryId = getArguments().getInt("CategoryId");
		couponCode = getArguments().getString("CouponCode");
		currencyCode = getArguments().getString("currencyCode");
		currencyCodeStr = getArguments().getString("currencyCodeStr");
		if(0==position){
			productlist = getArguments().getParcelableArrayList("productlist");
		}
		if (null != productlist) {
			List<ProductModel> products = productlist;
			productsList.addAll(products);
		}
		getSavedData(savedInstanceState);
	}
	
	/**
	 * 获取Fragment销毁后保存的数据 
	 * //由于Lp页面可能品类很多使用的Fragment会比较多
	 * 所以Adapter使用FragmentStatePagerAdapter 该适配器特点是 当fragment不可见时立刻
	 * 销毁释放内存资源 所以需要在销毁前保存数据
	 * @param savedInstanceState
	 */
	private void getSavedData(Bundle savedInstanceState){
		if(null!=savedInstanceState){
			List<ProductModel> products =savedInstanceState.getParcelableArrayList("ProductsList");
			if(null!=products&&products.size()>0){
				//此时获取到数据 代表是由销毁钱保存的数据 不是由Coupon列表携带的数据
				productsList.clear();
				productsList.addAll(products);
			}
			currentPosition=savedInstanceState.getInt("CurrentPosition");
			couponCode=savedInstanceState.getString("CouponCode");
			position=savedInstanceState.getInt("Position");
			sortType=savedInstanceState.getString("CurrentType");
			currencyCode=savedInstanceState.getString("currencyCode");
			currencyCodeStr=savedInstanceState.getString("currencyCodeStr");
		}
		
	}
	
	@SuppressLint("ValidFragment")
	public LandingPageCategoryFragment(Context context) {
		this.mContext = context;
	}
	public LandingPageCategoryFragment(){}
	public static LandingPageCategoryFragment newInstance(int position,int categoryId,
			ArrayList<ProductModel> productList,
			String couponCode,OnFlingStateChangedListener onFlingStateChangedListener,
			String currencyCode,String currencyCodeStr) {
		LandingPageCategoryFragment f = new LandingPageCategoryFragment(onFlingStateChangedListener);
		Bundle b = new Bundle();
		b.putInt("CategoryId", categoryId);
		b.putInt("Position", position);
		b.putParcelableArrayList("productlist", productList);
		b.putString("CouponCode", couponCode);
		b.putString("currencyCode", currencyCode);
		b.putString("currencyCodeStr", currencyCodeStr);
		f.setArguments(b);
		return f;
	}

	public LandingPageCategoryFragment(OnFlingStateChangedListener onFlingStateChangedListener) {
		this.onFlingStateChangedListener = onFlingStateChangedListener;
	}

	@Override
	public void onAttach(Activity activity) {
		this.mContext = activity;
		this.listenner=(OnFragmentCreateViewCalled) activity;
//		parentActivity = (LandingPageActivity) activity;
//		parentActivity.setOnSortChangeListenner(this);
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		Logger.i("YYY", "rootView: " + rootView);
		if (rootView == null) {
			rootView = inflate(R.layout.fragment_landing_page_categroy);
			intView(rootView);
			initData();
			initEvent();
			if(/*position!=0||(position==0&&*/(null==productsList||productsList.size()==0)){
				showLoadingLayout(productsLayout);
				AsyncTaskUtil.executeTask(new GetCategoryProducts(pageIndex, categoryId,
						couponCode));
			}
			
		}
		if (null == mContext) {
			mContext = getActivity();
		}
		if(null!=listenner){
			//再次执行时 通知宿主Activity执行上次排序样式还原操作 由于使用FragmentStatePagerAdapter
			//Fragment不可见时 已经被销毁  
			listenner.onCreateViewCalled(sortType,position);
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		return rootView;
	}

	private void intView(View rootView) {
		productsLayout=(RelativeLayout) rootView.findViewById(R.id.products_layout);
		gridViewLayout = (PullToRefreshGridView) rootView
				.findViewById(R.id.data_list);
		toTop=(ImageButton) rootView.findViewById(R.id.productlist_totop);
		if (null != errorLayout) {
			errorLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					showLoadingLayout(productsLayout);
					AsyncTaskUtil.executeTask(new GetCategoryProducts(pageIndex, categoryId,
							couponCode));

				}
			});
		}
	}

	protected int getDensityDpi() {
		DisplayMetrics metrics = new DisplayMetrics();
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		display.getMetrics(metrics);
		return metrics.densityDpi;
	}

	/**
	 * 加载数据
	 */
	public void initData() {
		// 给listView添加适配器
		adapterProduct = new ProductListAdapter(mContext, productsList, false,
				gridViewLayout, this, getDensityDpi(),tracker);
		adapterProduct.setCurrencyCode(currencyCode, currencyCodeStr);
		gridViewLayout.setAdapter(adapterProduct);
		if(productsList.size()>=0){
			if(productsList.size()<Constant.LIST_PAGE_COUNT){
				gridViewLayout.setMode(Mode.PULL_FROM_START);
			}else{
				gridViewLayout.setMode(Mode.BOTH);
			}
			Logger.i(TAG, "getRefreshableView set Selection");
			gridViewLayout.getRefreshableView().setSelection(currentPosition);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		//销毁Fragment之前 保存数据
		outState.putParcelableArrayList("ProductsList", productsList);
		int currentPosition=gridViewLayout.getRefreshableView().getFirstVisiblePosition();
		outState.putInt("CurrentPosition", currentPosition);
		outState.putString("CouponCode", couponCode);
		outState.putInt("Position", position);
		outState.putString("CurrentType", sortType);
		outState.putString("currencyCode", currencyCode);
		outState.putString("currencyCodeStr", currencyCodeStr);
		super.onSaveInstanceState(outState);
	}

	/**
	 * 加载事件
	 */
	private void initEvent() {
		// listView的下拉刷新与上拉加载
		gridViewLayout.setOnRefreshListener(new OnRefreshListener2<GridView>() {
			@Override
			public void onPullDownToRefresh( 
					PullToRefreshBase<GridView> refreshView) {
				pageIndex = 0;
				productsList.clear();
				if (null != adapterProduct) {
					adapterProduct.setFirstEnter(true);
				}
				AsyncTaskUtil.executeTask(new GetCategoryProducts(pageIndex, categoryId,
						couponCode));
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<GridView> refreshView) {
//			
			}
		});
		//返回列表顶部
		toTop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				gridViewLayout.getRefreshableView().setSelection(0);
			}
		});
	}

	// +++++++++++++++获取订单数据的任务++++++++++++++++++++++

	protected class GetCategoryProducts extends AsyncTask<Void, Void, String> {
		private CouponActiveModel couponActiveModel;
		private int start;
		private int categoryId;
		private String couponCode;

		public GetCategoryProducts(int start, int categoryId, String couponCode) {
			this.start = start;
			this.categoryId = categoryId;
			this.couponCode = couponCode;
		}

		@Override
		protected void onPreExecute() {
			isLoading=true;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				couponActiveModel = ProviderFactory
						.createCouponServiceProvider().FindDiscountProducts(
								couponCode, Constant.LIST_PAGE_COUNT, start,
								categoryId,sortType,ActivityUtil.getCustomerID(),OnekeyFilterLocalUtil.getFilterState(getActivity()),OnekeyFilterLocalUtil.getLocalCategoryIds(getActivity()));
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			if (!isDetached()) {
				// 加载任务执行完毕，隐藏加载视图
				if (start == 0) {
					hideAllLayout(productsLayout);
				}
				if ("0".equals(result)) {
					if (null != couponActiveModel) {
						List<ProductModel> products = couponActiveModel
								.getProducts();
						if (null != products && products.size() > 0) {
							if(products.size()<Constant.LIST_PAGE_COUNT){
								gridViewLayout.setMode(Mode.PULL_FROM_START);
							}else{
								gridViewLayout.setMode(Mode.BOTH);
							}
							productsList.addAll(products);
							adapterProduct.setCurrencyCode(couponActiveModel.getCurrencyCode(), couponActiveModel.getCurrencyCodeStr());
							if(isReLoad){
								adapterProduct.notifyDataSetInvalidated();
								isReLoad=false;
							}else{
								adapterProduct.notifyDataSetChanged();
							}
							
							gridViewLayout.onRefreshComplete();
							// 集合中的数据是否小于列表每次加载数据数量
							if (products.size() < Constant.LIST_PAGE_COUNT) {
								gridViewLayout.setMode(Mode.PULL_FROM_START);
							} else {
								gridViewLayout.setMode(Mode.BOTH);
							}
						} else {
							gridViewLayout.onRefreshComplete();
							if (0 == start) {
								showEmptyByErrorLayout(productsLayout,
										R.string.no_products_suggest,
										R.drawable.sorry);
							} else {
								gridViewLayout.setMode(Mode.PULL_FROM_START);
								adapterProduct.notifyDataSetChanged();
							}
						}
					}else{
						gridViewLayout.onRefreshComplete();
						if (0 == start) {
							showEmptyByErrorLayout(productsLayout,
									R.string.no_products_suggest,
									R.drawable.sorry);
						} else {
							gridViewLayout.setMode(Mode.PULL_FROM_START);
							adapterProduct.notifyDataSetChanged();
						}
						
					}
				} else {
					// 加载第一页因网络未连接或者超时显示网络异常页面
					if (0 == start) {
						showErrorLayout(productsLayout,
								R.string.internet_error,
								R.string.internet_suggest,
								R.drawable.no_internet);
						retryBtn.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								hideAllLayout();
								AsyncTaskUtil
										.executeTask(new GetCategoryProducts(
												start, categoryId, couponCode));
							}
						});
					} else {
						gridViewLayout.onRefreshComplete();
						pageIndex--;
						gridViewLayout.setMode(Mode.BOTH);
						AlertToast.alert(mContext,
								ServerConstant.ReturnCode.MESSAGEMAP
										.get(result));
					}
				}
				isLoading=false;
				if(getActivity()!=null){
					((LandingPageActivity)getActivity()).setSortEnable(true);
				}
			}

		}

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// 判断列表当前可见的第一条数据位置，设置返会顶部按钮是否可见
		if (view.getFirstVisiblePosition() > 4) {
			toTop.setVisibility(View.VISIBLE);
		} else {
			toTop.setVisibility(View.GONE);
		}
		//判断滚动的方向
		if(visibleItemCount>0){
			if(firstVisibleItem!=firstVisibalNum){
				boolean isScroll2Top = true;
	        	if(firstVisibleItem>firstVisibalNum){//向上滑动
	        		isScroll2Top = true;
	        	}else{//向下滑动
	        		isScroll2Top = false;
	        	}
	        	firstVisibalNum = firstVisibleItem;
	        	if(isScroll2Top != mIsScroll2Top){//滑动方向发生变化
		        	mIsScroll2Top = isScroll2Top;
					if(onFlingStateChangedListener!=null){
						if(isFirstIn){
							mIsScroll2Top = !mIsScroll2Top;
							isFirstIn = false;
							return;
						}
						if(isOnTouching && mIsScroll2Top && firstVisibleItem!=0){
							mIsScroll2Top = !mIsScroll2Top;
							return;
						}
						onFlingStateChangedListener.onFlingToTop(mIsScroll2Top);
					}
				}
	        }
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
			isOnTouching = true;
			break;
		case OnScrollListener.SCROLL_STATE_FLING:
			isOnTouching = false;
			break;
		case OnScrollListener.SCROLL_STATE_IDLE:
			isOnTouching = false;
			firstVisiblePosition = view.getFirstVisiblePosition() + 2;
			break;

		default:
			break;
		}
		// 实现预加载功能
		int autoLoadCount = productsList.size() - view.getFirstVisiblePosition();
		if (autoLoadCount < 8 && !isLoading) {
			pageIndex++;
			AsyncTaskUtil.executeTask(new GetCategoryProducts(pageIndex, categoryId,
					couponCode));
		}
	}

	/*@Override
	public void onSortChange(String sortType,int position) {
		this.sortType=sortType;
		Log.i("YYY", sortType+ position+ " "+this.position);
		if(this.position==position+1){
			sortRequest(sortType);
		}
	}*/
	
	/**
	 * 排序请求
	 */
	public void sortRequest(String sortType) {
		this.sortType=sortType;
		pageIndex = 0;
		productsList.clear();
		if (null != adapterProduct) {
			adapterProduct.setFirstEnter(true);
		}
		showLoadingLayout(productsLayout);
		isReLoad = true;
		AsyncTaskUtil.executeTask(new GetCategoryProducts(pageIndex, categoryId,
				couponCode));
	}
	
	public String getCurrentFragmentSortType(){
		return sortType;
	}
	
	public interface OnFragmentCreateViewCalled{
		void onCreateViewCalled(String sortType,int position);
	}
	
	/**
	 * @author tony
	 * desc:列表滑动状态变化监听
	 */
	public interface OnFlingStateChangedListener{
		void onFlingToTop(boolean isToTop);
	}

}
